# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

import logging
import time

from celery import shared_task
from django.conf import settings

from demo.demo_access_mgmt.models import User
from demo.demo_access_mgmt.serializers import UserSerializer
from demo_common_module.utils.ldap_utils import LdapSyncUtils

logger = logging.getLogger("info")


@shared_task
def refresh_plan_status():
    # 调取审批流的审批状态
    pass


@shared_task
def sync_ldap_to_user():
    ldap_sync = LdapSyncUtils()
    objCon, ObjInit = ldap_sync.bind_Connect()

    start_timestamp = time.time()

    # 取除所有用户的信息
    mysql_user_objs = User.objects.all()

    # user的id列表
    mysql_user_ids = [user_obj.user_id for user_obj in mysql_user_objs]
    # user_id与user_obj的映射关系
    mysql_user_id_objs = {user_obj.user_id: user_obj for user_obj in mysql_user_objs}

    for location in settings.LDAP_LOCATIONS:
        dicUserData = ldap_sync.get_UserData(location, settings.LDAP_COLUMN_MAPPING)

        # 根据基地名来过滤用户
        # 匹配基地名
        # location = re.search("^OU=([\w]{4}),", location).group(1)
        #
        # # 查包含基地的user信息
        # mysql_user_objs = User.objects.filter(location__contains=location)
        # if location == "SHDC":
        #     mysql_user_objs = User.objects.filter(user_id__startswith="V")
        #
        # # user的id列表
        # mysql_user_ids = [user_obj.user_id for user_obj in mysql_user_objs]
        # # user_id与user_obj的映射关系
        # mysql_user_id_objs = {user_obj.user_id: user_obj for user_obj in mysql_user_objs}
        add_user_list = list()
        # 遍历基地的用户信息
        for item in dicUserData:
            ldap_user_id = item.get("user_id")
            ldap_user_status = item.get("status")
            ldap_user_name = item.get("user_name")
            ldap_location = item.get("location")
            if ldap_user_id in mysql_user_ids:
                mysql_user_obj = mysql_user_id_objs.get(ldap_user_id)
                mysql_user_status = mysql_user_obj.status
                mysql_user_name = mysql_user_obj.user_name
                mysql_location = mysql_user_obj.location
                if ldap_user_status != mysql_user_status:
                    user_serializer = UserSerializer(mysql_user_obj, item)
                    user_serializer.is_valid(raise_exception=True)
                    user_serializer.save()
            else:
                add_user_list.append(item)

        serializer = UserSerializer(data=add_user_list, many=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

    ldap_sync.close_ldapConn(ObjInit)

    end_timestamp = time.time()

    logger.info("ldap data is synchronized to the user table (successful), time consuming:{}".format(
        end_timestamp - start_timestamp))

    return "ldap data is synchronized to the user table (successful), time consuming:{}".format(
        end_timestamp - start_timestamp)
